/** 请求封装 */
import axios from 'axios';
import { URL } from './http-url';
import { httpHead } from './http-header';
import { showError } from './error';

axios.defaults.baseURL = URL;
axios.defaults.timeout = 30000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

/**
 * 请求方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} headers [请求头]
 * @param {Boolean} showToast [是否显示错误提示toast]
 */
export default function http({
    url,
    data = {},
    method = 'post',
    headers = httpHead(),
    showToast = true
  }) {
  return new Promise((resolve, reject) => {
    if (method === 'get') {
      // 将请求参数拼接到url中
      let params = '';
      for (let [key, value] of Object.entries(data)) {
        console.log(key + ": " + value);
        params = params + `${key}=${value}&`
      }
      if (params.length > 0) {
        params = '?' + params;
        params = params.slice(0, -1);
      }
      url = url + params;
    }
    axios({ headers, method, url, data }).then(res => {
      if (res.data.code === 0) {
        const urlParts = url.split('/');
        const interfaceName = urlParts[urlParts.length - 1];
        console.log(interfaceName + '===>', res.data)
        resolve(res.data);
      } else {
        console.error(res);
        if (showToast) showError(res.data);
        resolve(res.data)
      }
    }).catch(err => {
      console.error(err)
      reject(err.data)
    })
  });
}